package com.feihong.txgw.ui.activity.setting;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.inter.listener.web.SystemMessagecontent;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.SystemMsgMessage;
import com.feihong.txgw.ui.activity.base.BaseActivity;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.manage.ThreadPoolManager;
import com.feihong.txgw.utils.sign.SignToken;
import com.just.agentweb.AgentWeb;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;

import butterknife.BindView;

/**
 * Created by PVer on 2017/8/3.
 * 消息列表页面
 */

public class MessageContentActivity extends BaseActivity {


    private RelativeLayout webviewFrame;
    private AgentWeb mAgentWeb;
    private AgentWeb.PreAgentWeb mPreAgentWeb;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mRequeryDataBtn;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if(activityIsDestory()){
                return;
            }
            if (msg.what == 10) {
                loadPage();
            }else if(msg.what == 11){
                mConnectErrorLayout.setVisibility(View.VISIBLE);
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_messagecomtent;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        setBackButtonFinish();
        setPageTitle("消息列表");
        webviewFrame = (RelativeLayout) findViewById(R.id.webviewframe);
        mRequeryDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshToken();
            }
        });
        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(webviewFrame, new RelativeLayout.LayoutParams(-1, -1))//
                .useDefaultIndicator()
                .setMainFrameErrorView(R.layout.agentweb_errorlayout,R.id.agentweb_re_query_data_layout)
                .setWebViewClient(mWebViewClient)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .createAgentWeb()
                .ready();
    }

    //WebViewClient
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };
    //WebChromeClient
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
    };

    @Override
    public void bindData() {
        refreshToken();
//        if (mAgentWeb == null) {
    }

    private void loadPage() {
        String url = "";
        String params = new SignToken().setSigen(new HashMap<String, String>());
        url = HttpTools.MESSAGE_SYSTEM_LIST + "?" + params;
        LogUtils.i(TAG+ " :消息列表url:" + url);
        // Activity用法
        mAgentWeb = mPreAgentWeb.go(url);

        //屏蔽长按弹出复制按钮
        mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        // js调用安卓
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new SystemMessagecontent(mAgentWeb, this, new ActionCallBack() {
            @Override
            public String get_result(String par) {
                HashMap<String, String> params = new HashMap<>();
                try {
                    JSONObject jsonObject = new JSONObject(par);
                    Iterator<String> maps = jsonObject.keys();
                    while (maps.hasNext()) {
                        String key = maps.next();
                        String val = jsonObject.getString(key);
                        //url = url + "&" + key + "=" + val;
                        params.put(key, val);
                    }
                } catch (JSONException e) {
                    // 数据解析异常
                    e.printStackTrace();
                }
                String getParams = new SignToken().setSigen(params);
                return getParams;
            }


            @Override
            public String go_Detail(String info) {
                LogUtils.i(TAG + ": 消息详情：" + info);
                if (info == null || info.length() == 0) {
                    ToastUtils.getInstance().showShortToast("数据错误！");
                }
                try {
                    JSONObject obj = new JSONObject(info);
                    String url = obj.getString("url");
                    String id = obj.getString("id");
                    String is_read = obj.optString("is_read");
                    Intent details = new Intent(MessageContentActivity.this, MessageDetailsActivity.class);
                    details.putExtra("url", url);
                    details.putExtra("id", id);
                    details.putExtra("is_read", is_read);
                    details.putExtra(MessageDetailsActivity.MESSAGE_TYPE, MessageDetailsActivity.MESSAGE_LIST_TYPE);
                    startActivity(details);

                } catch (Exception e) {
                    e.printStackTrace();
                }

                return info;
            }
        }));
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    public interface ActionCallBack {
        public String get_result(String par);

        public String go_Detail(String info);
    }

    private void refreshToken() {
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                RefreshToken.getInstance().RetrofitRefreshTokenForGet();
                Message message = Message.obtain();
                message.what = 10;
                mHandler.sendMessage(message);
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAgentWeb != null) {
            mAgentWeb.destroy();
        }
        if(mHandler != null && mHandler.getLooper() == Looper.getMainLooper()){
            mHandler.removeCallbacksAndMessages(null);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshMsgContent(SystemMsgMessage systemMsgMessage) {
        if (mAgentWeb != null) {
            mAgentWeb.getUrlLoader().reload();
        }
    }
}
